package com.boatAnchorAssistant.service.service.impl;

import com.boatAnchorAssistant.pojo.entity.Resource;
import com.boatAnchorAssistant.pojo.event.resource.CreateResourceEvent;
import com.boatAnchorAssistant.pojo.param.resource.*;
import com.boatAnchorAssistant.pojo.resource.MetaDto;
import com.boatAnchorAssistant.service.repository.in.ResourceRepository;
import com.boatAnchorAssistant.service.service.in.ResourceService;
import nirvana.core.utils.ids.IdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import java.util.List;

/**
 * 【描 述】：资源服务
 * 【环 境】：J2SE 17
 * 【详 细】：
 *
 */
@Service
public class ResourceServiceImpl implements ResourceService {

    private final ResourceRepository resourceRepository;

    private final ApplicationEventPublisher publisher;

    public ResourceServiceImpl(ResourceRepository resourceRepository, ApplicationEventPublisher publisher) {
        this.resourceRepository = resourceRepository;
        this.publisher = publisher;
    }


    /**
     * 批量上传资源
     *
     * @param paramList
     * @param parentId
     */
    @Override
    public void bathUploadResource(List<BathUploadResourceParam> paramList, Long parentId) {
        for (int i = 0; i < paramList.size(); i++) {
            BathUploadResourceParam param = paramList.get(i);


            Long paramParentId = param.getParentId();
            if (paramParentId != null) {
                parentId = paramParentId;
            }

            Long id = IdGenerator.SNOW.generate();

            Resource resource = new Resource();
            BeanUtils.copyProperties(param, resource);
            resource.setId(id);
            resource.setParentId(parentId);

            MetaDto meta = param.getMeta();
            if (meta != null) {
                resource.setResourceName(meta.getTitle());
            }
            resource.setDisplayOrder(i);
            resource.setType(param.getType());

            //发送创建资源事件
            CreateResourceEvent event = new CreateResourceEvent();
            event.setId(id);
            event.setParentId(parentId);
            publisher.publishEvent(event);

            resourceRepository.create(resource);
            //如果还有下级，就递归
            List<BathUploadResourceParam> children = param.getChildren();
            if (!CollectionUtils.isEmpty(children)) {
                bathUploadResource(children, id);
            }
        }
    }
}



